﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using MLMBonus.Engine;
using MLMBonus.Unilevel.Properties;

namespace MLMBonus.Unilevel
{
    public class Distributor : NodeBase
    {
        public Distributor(UnilevelContext Context) : base((IBonusContext)Context) { }

        #region Useful properties
        public decimal PV { get; set; }
        public decimal GV { get; set; }
        public decimal OV { get; set; }

        public int OriginalRankId { get; set; }
        public int CurrentRankId { get; set; }
        public int ActiveLegs { get; set; }
        public int Breakaways { get; set; }
        internal int qualifiedUnilevels { get; set; }
        internal int? qualifiedGenerations { get; set; }

        private XElement currentRank { get; set; }

        public DistributorFlags Flags { get; set; }

        public bool IsRetail { get; set; }
        public bool IsBreakaway { get; set; }
        internal bool isQualifiedBreakaway { get; set; }
        #endregion

        #region Calculated properties
        internal UnilevelContext uniContext
        {
            get
            {
                return (UnilevelContext)Context;
            }
        }

        public bool IsActive
        {
            get
            {
                if (Flags.IsActive.HasValue)
                    return Flags.IsActive.Value;
                
                return this.PV >= Settings.Default.ActivePVReq;
            }
        }

        internal Distributor responsibleDistributor
        {
            get
            {
                if (this.IsRetail && this.Parent != null)
                {
                    return ((Distributor)this.Parent).responsibleDistributor;
                }
                return this;
            }
        }
        #endregion

        #region Bonus engine methods
        // These are the heavy lifters that do the actual work.
        protected override void RunPreProcess(string BonusRunType)
        {
            string origRankId = this.Flags.RankOverride.HasValue ? this.Flags.RankOverride.Value.ToString() : this.OriginalRankId.ToString();
            XElement rank = (from elem in uniContext.rankConfig.Descendants("Rank")
                             where elem.Attribute("id").Value == origRankId
                             select elem).First();
            currentRank = rank;

            this.IsRetail = UnilevelContext.isRetail(rank);
            this.IsBreakaway = UnilevelContext.isBreakaway(rank);

            foreach (Order order in this.Volumes)
            {
                this.PV += order.PV;
                order.OriginatingDistributor = this;
                order.PVDistributor = this.responsibleDistributor;
            }
            this.GV = this.OV = this.PV;

            if (this.IsRetail)
            {
                if (!responsibleDistributor.Equals(this))
                {
                    responsibleDistributor.PV += this.PV;
                }
            }
        }

        protected override void RunPromote(string BonusRunType)
        {
            if (IsRetail)
                return;

            XElement qualifiedRank = uniContext.LowestNonRetailRank;
            foreach (XElement rank in uniContext.OrderedRanks)
            {
                if (checkReq(rank.Element("PVReq"), PV))
                    break;
                if (checkReq(rank.Element("GVReq"), GV))
                    break;
                if (checkReq(rank.Element("ActiveLegReq"), ActiveLegs))
                    break;
                if (checkReq(rank.Element("BreakawayReq"), Breakaways))
                    break;

                qualifiedRank = rank;
            }

            qualifiedRank = checkQualRankOverride(qualifiedRank);

            currentRank = qualifiedRank;

            qualifiedUnilevels = int.Parse(qualifiedRank.Element("Unilevels").Value);
            if (qualifiedRank.Element("Generations") == null)
            {
                qualifiedGenerations = null;
            }
            else
            {
                qualifiedGenerations = int.Parse(qualifiedRank.Element("Generations").Value);
            }

            int qualRankId = int.Parse(qualifiedRank.Attribute("id").Value);
            if (qualRankId > CurrentRankId)
            {
                Context.Promote(this, CurrentRankId.ToString(), qualifiedRank.Attribute("id").Value);
            }

            if (qualifiedRank.Element("IsBreakaway") != null)
            {
                isQualifiedBreakaway = qualifiedRank.Element("IsBreakaway").Value.Equals("true", StringComparison.InvariantCultureIgnoreCase);
            }
        }

        protected override void RunPostProcess(string BonusRunType)
        {
            Distributor parent = this.Parent as Distributor;
            if (parent != null)
            {
                parent.OV += this.OV;

                if (this.IsBreakaway)
                {
                    parent.Breakaways += 1;
                }
                else
                {
                    parent.GV += this.GV;
                    parent.Breakaways += this.Breakaways;
                }

                if (this.IsActive || this.ActiveLegs > 0)
                {
                    parent.ActiveLegs += 1;
                }
            }
        }
        #endregion

        private bool checkReq(XElement req, decimal value)
        {
            return req != null && decimal.Parse(req.Value) > value;
        }

        private bool checkReq(XElement req, int value)
        {
            return req != null && int.Parse(req.Value) > value;
        }

        private XElement checkQualRankOverride(XElement qualifiedRank)
        {
            if (Flags.RankOverride.HasValue)
            {
                int qualRank = int.Parse(qualifiedRank.Attribute("id").Value);
                if (Flags.RankOverride.Value > qualRank)
                {
                    XElement rankToUse = (from rank in uniContext.rankConfig.Descendants("Rank")
                                          where rank.Attribute("id").Value == (Flags.RankOverride ?? 0).ToString()
                                          select rank).FirstOrDefault();

                    if (rankToUse != null)
                    {
                        return rankToUse;
                    }
                }
            }

            return qualifiedRank;
        }
    }

    public struct DistributorFlags
    {
        public bool? IsActive;
        public int? RankOverride;
    }
}
